package com.origin.learn.dbpool;

import java.sql.Connection;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Description: 自定义的通用连接池，可以直接继承此连接池，然后实现createConnection()方法即可。获取直接仿照此类写一个
 * @Date: 2020/2/28
 * @Time: 20:19
 * @Created by:   dingtao
 * @Modified by:
 * @Modified at:
 */
public class CommonConnectionPool extends AbstractConnectionPool implements ConnectionPool {

    /**
     * 连接池初始大小
     */
    private int initSize;
    /**
     * 连接池正常数量
     */
    private int coreSize;
    /**
     * 连接池最大大小
     */
    private int maxSize;
    /**
     * 连接池检查池中连接数量的间隔时间
     */
    private long checkIntervalTime;

    /**
     * 连接池是否存活，false时需要关闭线程池
     */
    private boolean isAlive;

    private BlockingQueue<Connection> pool;

    public CommonConnectionPool(int initSize, int coreSize, int maxSize, long checkIntervalTime){
        if (initSize>0&&initSize<coreSize&&coreSize<maxSize){
            this.initSize = initSize;
            this.coreSize = coreSize;
            this.maxSize = maxSize;
            this.checkIntervalTime = checkIntervalTime;
            this.isAlive = true;
            this.pool = new LinkedBlockingQueue<>();
        }else {
            throw new IllegalArgumentException("连接池初始化大小设置不合理");
        }
    }

    @Override
    public int getInitSize() {
        return initSize;
    }


    @Override
    public int getCoreSize() {
        return coreSize;
    }

    @Override
    public int getMaxSize() {
        return maxSize;
    }

    @Override
    public long getCheckIntervalTime() {
        return checkIntervalTime;
    }

    @Override
    public BlockingQueue<Connection> getPool() {
        return pool;
    }

    @Override
    public boolean isAlive() {
        return isAlive;
    }

    @Override
    public void kill() {
        isAlive = false;
    }

    @Override
    public Connection createConnection() {
        throw new UnsupportedOperationException();
    }
}
